<!-- 简单列表封装 -->
<template>
  <el-button type="primary" style="width:100%" @click="add">添加</el-button>
  <ul style="overflow: auto" class="custom-list">
    <li 
      v-for="(item, index) in pageList" 
      :key="item.id" 
      @click="handleClick(item.id)"
      :class="{ 'selected': item.id === selectedId }"
    >
      <el-row type="flex" justify="space-between" align="middle">
        <el-col :span="18">
          <el-text>{{item.name}}</el-text>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button link :icon="Delete" @click="deleteItem(item.id)"></el-button>
        </el-col>
      </el-row>
    </li>
  </ul>
  <el-pagination layout="prev, pager, next" :total="list.length"
    v-model:current-page="curPage" :page-size="pageSize"></el-pagination>

    <el-pagination layout="jumper" :total="list.length"
    v-model:current-page="curPage" :page-size="pageSize"></el-pagination>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue';
import { Delete } from '@element-plus/icons-vue';
let pageIdx = ref(0)
let pageList = ref<any[]>([])
let pageSize = ref(10)
const curPage = computed({
  get: ()=> pageIdx.value + 1,
  set: (val) =>{
    pageIdx.value = val - 1
    console.log("curPage changed")
    updateList()
  }
})
const props = defineProps<{
  list:any[]
  selectedId?: number | null
}>()
const emit = defineEmits<{
  (event: "delete", id:number): void;
  (event: "add"): void;
  (event: "click", id:number):void;
}>()
let updateList = ()=>{
  pageList.value.splice(0, pageList.value.length)
  let start = pageIdx.value * pageSize.value
  for (let i = 0; i < pageSize.value; i++) {
    let idx = i + start
    if (idx < props.list.length) {
      pageList.value.push(props.list[idx])
    }
  }
}
watch(
  ()=> props.list.length,
  (newVal)=>{
    updateList()
  }
)

console.log("SimpleList inited")
updateList()
let add = ()=>{
  emit("add")
}
let deleteItem = (id:number)=>{
  emit("delete", id)
}

let handleClick = (id: number) => {
  console.log("onclick", id)
  emit("click", id);
}
</script>

<style scoped>
/* 去掉ul默认的列表样式 */
.custom-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.container {
  padding: 16px;
  height: 50%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.pagination-container {
  margin-top: auto;
  padding: 12px 0;
  justify-content: flex-end;
}

:deep(.el-pagination__jump) {
  margin-left: 12px;
}

li.selected {
  background-color: #f5f7fa;
  border-left: 4px solid #409eff;
  transition: all 0.3s ease;
}

li:hover {
  background-color: #f0f4f8;
  cursor: pointer;
}
</style>